package com.group3.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.group3.Feign.PaymentSeviceFeign;
import com.group3.Feign.ProductServiceFeign;
import com.group3.Feign.UserServiceFeign;
import com.group3.common.result.ApiResponse;
import com.group3.model.Order;
import com.group3.model.Payment;
import com.group3.model.Product;
import com.group3.model.User;
import com.group3.service.OrderSevice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {


    @Autowired
    UserServiceFeign userServiceFeign ;
    @Autowired
    ProductServiceFeign productServiceFeign ;
    @Autowired
    OrderSevice orderSevice;
    // 新增支付服务Feign客户端调用
    @Autowired
    PaymentSeviceFeign paymentSeviceFeign;
    @SentinelResource ("getProductById")
    @RequestMapping("/add")
    public ApiResponse addOrder(@RequestParam(name = "uid") Integer uid ,@RequestParam(name = "pid") Integer pid){
        if (pid==-1){
            throw   new RuntimeException("商品服务不可用");
        }
        User user=userServiceFeign.getUserByUid(uid);
        Product product=productServiceFeign.getProductByPid(pid);
        boolean is=  productServiceFeign.decreaseStock(pid,1);
        if ((user.getUid() == -999)){
            return  new ApiResponse<>(500,"下单失败",user);
        }

        if (user!=null&&product!=null&&is){
            Order order=new Order();
            order.setUid(user.getUid());
            order.setUsername(user.getUsername());
            order.setPid(pid);
            order.setPname(product.getPname());
            order.setPprice(product.getPprice());
            order.setNumber(1);
            order.setStatus(0);
            try {
                orderSevice.addOrder(order);
            }catch ( Exception e){
                productServiceFeign.increaseStock( pid,1);
            }

            return ApiResponse.success("下单成功",order);
        }
        return ApiResponse.error("下单失败");
    }
    @SentinelResource("getProductById")
    @RequestMapping ("/getOrderProduct/{oid}")
    public ApiResponse getOrderProduct( @PathVariable Integer oid){
        Order order=orderSevice.getOrderByOid(oid);
       Product product=productServiceFeign .getProductByPid( order.getPid());
        return  ApiResponse.success("获取成功",product);
    }


    @RequestMapping("/getOrderListbyUid/{uid}")
    public List<Order> getOrderListbyUid(@PathVariable Integer uid){
        List<Order> orderList=orderSevice.getOrderListbyUid(uid);
        return orderList;
    }


    @RequestMapping("/getOrderByOid/{id}")
    public Order getOrderByOid(@PathVariable Integer id){
        Order order=orderSevice.getOrderByOid(id);
        return order;
    }
    @Transactional
    @PostMapping("/updateOrder")
    public boolean updateOrder(@RequestBody Order order){
        return orderSevice.updateOrder(order);
    }

    // 新增支付订单接口
    @RequestMapping("/payOrder/{oid}")
    public ApiResponse payOrder(@PathVariable Integer oid) {
        Order order = orderSevice.getOrderByOid(oid);
        Payment payment=null;
        if (order!=null&&  order.getStatus() == 0) {
             payment = paymentSeviceFeign.paymentOrder(oid);
        }else {
            switch (order.getStatus()) {
                case 1:
                    return ApiResponse.success("订单已经支付",  order);
                 case 2:
                    return ApiResponse.success("订单已发货", order);
                case 3:
                    return ApiResponse.success("订单已完成",  order);
                case 4:
                    return ApiResponse.success("订单已取消",  order);
                case 5:
                    return ApiResponse.success("订单申请退款中",  order);
                case 6:
                    return ApiResponse.success("订单已退款",  order);
                default:
                    return ApiResponse.error("订单状态错误");
            }

        }


        if (payment.getId() ==null) {
            return ApiResponse.error("支付失败");
        }
        return ApiResponse.success("支付成功",  payment);
    }

    // 发货接口
    @RequestMapping("/deliverOrder/{oid}")
    public ApiResponse deliverOrder(@PathVariable Integer oid) {
        Order order = orderSevice.getOrderByOid(oid);
        if (order == null) {
            return ApiResponse.error("订单不存在");
        }
        if (order.getStatus() != 1) {
            return ApiResponse.error("订单未支付，无法发货");
        }

        order.setStatus(2);
        boolean updateResult = orderSevice.updateOrder(order);
        if (updateResult) {
            return ApiResponse.success("发货成功", order);
        }
        return ApiResponse.error("发货失败");
    }

    // 取消订单接口
    @RequestMapping("/cancelOrder/{oid}")
    public ApiResponse cancelOrder(@PathVariable Integer oid) {
        Order order = orderSevice.getOrderByOid(oid);
        if (order == null) {
            return ApiResponse.error("订单不存在");
        }
        Integer status = order.getStatus();
        if (status == 0) {
            order.setStatus(4);
            boolean updateResult = orderSevice.updateOrder(order);
            if (updateResult) {
                return ApiResponse.success("取消成功", order);
            }
        } else if (status == 1) {
            boolean refundResult = paymentSeviceFeign.refundOrder(oid);
            if (refundResult) {
                order.setStatus(4);
                boolean updateResult = orderSevice.updateOrder(order);
                if (updateResult) {
                    productServiceFeign .increaseStock(order.getPid(), order.getNumber());
                    return ApiResponse.success("取消成功，已退款", order);
                }
            } else {
                return ApiResponse.error("退款失败，取消订单失败");
            }
        } else {
            return ApiResponse.error("当前状态无法取消");
        }
        return ApiResponse.error("取消失败");
    }

    // 申请退款接口
    @RequestMapping("/applyRefund/{oid}")
    public ApiResponse applyRefund(@PathVariable Integer oid) {
        Order order = orderSevice.getOrderByOid(oid);
        if (order == null) {
            return ApiResponse.error("订单不存在");
        }
        if (order.getStatus() != 1 && order.getStatus() != 2) {
            return ApiResponse.error("当前状态无法申请退款");
        }
        order.setStatus(5);
        boolean updateResult = orderSevice.updateOrder(order);
        if (updateResult) {
            boolean refundInitiated = paymentSeviceFeign.initiateRefund(oid);
            if (refundInitiated) {
                return ApiResponse.success("退款申请已提交，处理中", order);
            } else {
                order.setStatus(order.getStatus());
                orderSevice.updateOrder(order);
                return ApiResponse.error("退款申请提交失败");
            }
        }
        return ApiResponse.error("申请退款失败");
    }
}
